package com.js.core.entity.result;

import java.io.Serializable;
import java.util.List;

/**
 * 统一返回结果封装类（适用于 JDK 17+）
 * 无静态方法，支持连缀风格
 */
public class ResultBean implements Serializable {
    private static final long serialVersionUID = 1L;

    public static final int CODE_SUCCESS = 200;
    public static final int CODE_ERROR = 500;
    public static final int CODE_WARNING = 501;
    public static final int CODE_NOT_JUR = 403;
    public static final int CODE_NOT_LOGIN = 401;
    public static final int CODE_INVALID_REQUEST = 400;

    private int code = CODE_SUCCESS;
    private String msg = "ok";
    private Object data;
    private Long dataCount;

    // 默认构造器
    public ResultBean() {
        this.code = CODE_SUCCESS;
        this.msg = "ok";
    }

    // 带参构造器
    public ResultBean(int code, String msg, Object data, Long dataCount) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.dataCount = dataCount;
    }

    // ========== 连缀风格的 setter ==========

    public ResultBean setCode(int code) {
        this.code = code;
        return this;
    }

    public ResultBean setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public ResultBean setData(Object data) {
        this.data = data;
        return this;
    }

    public ResultBean setDataCount(Long dataCount) {
        this.dataCount = dataCount;
        return this;
    }

    // ========== Getter ==========

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public Object getData() {
        return data;
    }

    public Long getDataCount() {
        return dataCount;
    }

    /**
     * 将 data 转换为指定类型返回（泛型安全）
     */
    @SuppressWarnings("unchecked")
    public <T> T getData(Class<T> type) {
        return (T) data;
    }

    /**
     * 是否成功（code == 200）
     * @return true 表示成功
     */
    public boolean isSuccess() {
        return this.code == CODE_SUCCESS;
    }

    /**
     * 是否失败（code != 200）
     * @return true 表示失败
     */
    public boolean isFail() {
        return !isSuccess();
    }

    // ========== toString ==========

    @Override
    public String toString() {
        String dataString = null;
        if (data == null) {
            dataString = "null";
        } else if (data instanceof List) {
            dataString = "List(size=" + ((List<?>) data).size() + ")";
        } else {
            dataString = data.toString();
        }

        return String.format(
                "{code=%d, msg='%s', data=%s, dataCount=%s}",
                code, msg, dataString, dataCount
        );
    }
}